package files_controller_with_factory;

import java.io.File; 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import org.apache.log4j.Logger;

public class MoveCommandExecutor implements ICommandExecutor{
	private static final Logger logger = Logger.getLogger(CopyCommandExecutor.class);
	private static final Logger cont_log = Logger.getLogger("control");
	
	public void execute(String string){
		String[] str_mas = string.split(" ");
		String source_path = str_mas[1];
		String dest_path = str_mas[2];
		String name = str_mas[3];
		String full_source_path = source_path.concat("\\").concat(name);
		File path_s = new File(full_source_path);
		String full_dest_path = dest_path.concat("\\").concat(name);
		File path_d = new File(full_dest_path);
		 
		try {
			Move(path_s, path_d);
			cont_log.info("Files have beem transfering from " + path_s.toString() + " to " + path_d.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			cont_log.warn("Error of input/output", e);
			//e.printStackTrace();
		}
	}
	
	private void Move(File f1, File f2) throws IOException{
		if(f1.isDirectory()){
			f2.mkdir();
			String[] list = f1.list();
			for(int i=0; i<list.length; i++){
				Move(new File(f1, list[i]), new File(f2, list[i]));
			}
			f1.delete();
			logger.info("Source directory " + f1.toString() + " successfully deleted");
			
		}else{
			f2.createNewFile();
			FileChannel inputChannel = null;
			FileChannel outputChannel = null;
			try{
				inputChannel = new FileInputStream(f1).getChannel();
				outputChannel = new FileOutputStream(f2).getChannel();
				outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
			}finally{
				inputChannel.close();
				outputChannel.close();
			}
			f1.delete();
			logger.info("File from source directory " + f1.toString() + " successfully deleted");
			
		}
	}
	
	private static MoveCommandExecutor instance;
	private MoveCommandExecutor(){			
	}
	public static ICommandExecutor getInstance(){
		if(instance==null){
			instance = new MoveCommandExecutor(); 
		}
		return instance;
	}
}